package com.le.edu.utils;


import com.alibaba.fastjson2.JSON;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket工具类
 */
@Slf4j
public class WebSocketRemoteContainerUtil {

    //保存用户与Session关系
    // 注意：websocket的Session不能序列化到redis，只能在内存中保存，集群环境配合redis广播，通知所有用户
    private static Map<Long, Session> userIdToSessionMap = new ConcurrentHashMap<>();

    public static void addSession(Long userId, Session session) {
        userIdToSessionMap.put(userId, session);
    }

    public static void removeSession(Long userId) {
        userIdToSessionMap.remove(userId);
    }

    public static Session getSession(Long userId) {
        return userIdToSessionMap.get(userId);
    }


    /**
     * 单发消息
     */
    public static void sendOneMsg(Long userId, String msg) {
        Session session = getSession(userId);
        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText(JSON.toJSONString(msg));//异步发送消息.
        }
    }


}
